package cn.yunhe.dplayerdemo3.controller;

import cn.yunhe.dplayerdemo3.Service.ICoinService;
import cn.yunhe.dplayerdemo3.Service.IUserInfoService;
import cn.yunhe.dplayerdemo3.entity.Coin;
import cn.yunhe.dplayerdemo3.entity.UserInfo;
import cn.yunhe.dplayerdemo3.entity.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class CoinController {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private ICoinService coinService;

    @RequestMapping("/addCoin")
    @ResponseBody
    public String addCoin(HttpServletRequest request, Model model) {
        int uid = Integer.parseInt(request.getParameter("uid"));
        int videoId = Integer.parseInt(request.getParameter("id"));
        int coinNum = Integer.parseInt(request.getParameter("coin"));
        Video video = new Video();
        video.setId(videoId);
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(videoId);
        UserInfo user = userInfoService.getUserInfoByName(new UserInfo(uid));
        if (user.getCoin() > coinNum) {
            if (userInfoService.updateUserInfo(coinNum, uid)) {
                Coin coin = new Coin(video, userInfo);
                coinService.addCoin(coin);
                return "succ";
            } else {
                return "error";
            }
        }
        return null;
    }
}
